﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;

namespace Pay.Api {
	public class ApiSign {
		public ApiSign() {
		}

		/// <summary>
		/// 平台的sign原始字符串
		/// </summary>
		/// <returns>The sign.</returns>
		/// <param name="model">Model.</param>
		public static string sign(JObject model) {
			var collection = model.ToObject<SortedDictionary<string, object>>();
			string result = string.Empty;
			foreach (var kv in collection) {
				if (kv.Key == "sign") continue;
				if (kv.Value is JArray) {
					string str = "";
					var arrs = kv.Value as JArray;
					foreach (var obj in arrs) {
						if (obj.Type.ToString().Equals("String")) continue;
						str += FillStringBuilder(obj.ToObject<SortedDictionary<string, object>>());
					}
					//str = str.Trim('&');
					//result += "&" + kv.Key + "=" + str;
					result += str;
				} else if (kv.Value is JObject) {
					//result += "&" + kv.Key + "=" + FillStringBuilder((kv.Value as JObject).ToObject<SortedDictionary<string, object>>());
					result += FillStringBuilder((kv.Value as JObject).ToObject<SortedDictionary<string, object>>());
				} else {
					  if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString())) {
                        if (kv.Value is DateTime) {
                            result += "&" + kv.Key + "=" + ((DateTime)kv.Value).ToString("yyyy-MM-dd HH:mm:ss");
                        } else
                            result += "&" + kv.Key + "=" + kv.Value;
                    }
				}
			}
			result = result.Trim('&');
			return result;
		}

		private static string FillStringBuilder(SortedDictionary<string, object> dic) {
			string result = string.Empty;
			foreach (var kv in dic) {
				if (kv.Value is JObject)
					//result += "&" + kv.Key + "=" + FillStringBuilder((kv.Value as JObject).ToObject<SortedDictionary<string, object>>());
					result += FillStringBuilder((kv.Value as JObject).ToObject<SortedDictionary<string, object>>());
				else if (kv.Value is JArray) {
					string str = "";
					var arrs = kv.Value as JArray;
					foreach (var obj in arrs) {
						if (obj.Type.ToString().Equals("String")) continue;
						str += FillStringBuilder(obj.ToObject<SortedDictionary<string, object>>());
					}
					//result += "&" + kv.Key + "=" + str;
					result += str;
				} else {
					  if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString())) {
                        if (kv.Value is DateTime) {
                            result += "&" + kv.Key + "=" + ((DateTime)kv.Value).ToString("yyyy-MM-dd HH:mm:ss");
                        } else
                            result += "&" + kv.Key + "=" + kv.Value;
                    }
				}
			}
			return result;
		}
	}
}
